<template>
  <!-- 角色表单弹窗 -->
  <el-dialog
    v-model="dialog.visible"
    :title="dialog.title"
    width="500px"
    height="500px"
    @close="handleCloseDialog"
    :close-on-click-modal="false"
  >
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick" type="card">
      <el-tab-pane label="绑定员工" name="first">
        <el-form
          ref="bindFormRef"
          :model="bindFormData"
          :rules="bindRules"
          label-width="100px"
          class="form"
        >
          <el-form-item label="手机号码" prop="mobile" required>
            <el-input
              v-model="bindFormData.mobile"
              placeholder="请输入手机号码查询"
              style="width: 200px"
            />
            <el-button class="ml-2" icon="Search" circle @click="handleSearch" />
            <!-- <el-button class="ml-10" type="primary" @click="handleSearch">查询</el-button> -->
          </el-form-item>
          <div class="flex flex-wrap gap-4">
            <el-card style="width: 480px" shadow="always" v-if="userData">
              <el-form-item label="用户名" class="mt-3">
                <el-input v-model="userData.nickname" style="width: 250px" disabled />
              </el-form-item>
              <el-form-item label="验证码" prop="code" required class="mt-3">
                <el-input
                  v-model="bindFormData.code"
                  placeholder="请输入验证码"
                  class="code-input"
                  style="width: 150px"
                />
                <el-button
                  class="send-code-btn"
                  :disabled="bindIsSending || bindCountdown > 0"
                  @click="sendBindCode"
                >
                  {{ bindCountdown > 0 ? `${bindCountdown}秒后重试` : "发送验证码" }}
                </el-button>
              </el-form-item>
              <div class="flex justify-end align-middle">
                <el-button class="ml-10" type="primary" @click="handleBindSubmit">绑定</el-button>
              </div>
            </el-card>
          </div>
        </el-form>
      </el-tab-pane>
      <!-- 新增员工 -->
      <el-tab-pane label="新增员工" name="second">
        <el-form
          ref="addEmployeFormRef"
          :model="addEmployeFormData"
          :rules="addEmployeRules"
          label-width="100px"
          class="form"
        >
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="addEmployeFormData.nickname" placeholder="请输入昵称" />
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input
              v-model="addEmployeFormData.phone"
              placeholder="请输入手机号码"
              clearable
            ></el-input>
          </el-form-item>

          <el-form-item label="验证码" prop="code">
            <el-input
              v-model="addEmployeFormData.code"
              placeholder="请输入验证码"
              class="code-input"
              style="width: 250px"
            />
            <el-button
              class="send-code-btn"
              :disabled="addEmployeIsSending || addEmployeCountdown > 0"
              @click="sendAddEmployeCode"
            >
              {{ addEmployeCountdown > 0 ? `${addEmployeCountdown}秒后重试` : "发送验证码" }}
            </el-button>
          </el-form-item>
        </el-form>
        <div class="flex justify-center align-middle">
          <el-button type="primary" style="width: 20%" @click="submitAddEmploye">新增</el-button>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="handleCloseDialog">取 消</el-button>
      </div>
    </template> -->
  </el-dialog>
</template>
<script setup>
import TermAPI from "@/api/term";
import CommonAPI from "@/api/system/common";
import { ElMessage } from "element-plus";
// 定义 emit，用于通知外部关闭事件
const emit = defineEmits(["update:modelValue", "handleBindSubmit"]);
// 弹窗
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  defaultRowId: {
    type: String,
    default: "",
  },
});

/**
 * 切换
 */
const activeName = ref("first");
// 弹窗状态绑定到内部变量
const dialog = reactive({
  title: "",
  visible: false,
});
/**
 * 绑定员工
 *
 *
 *
 */
const bindFormData = reactive({
  mobile: "",
  code: "",
});
const bindRules = reactive({
  mobile: [{ required: true, message: "请输入手机号码", trigger: "blur" }],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
});
const bindIsSending = ref(false);
const bindCountdown = ref(0);
const sendBindCode = () => {
  bindFormRef.value.validateField("mobile", async (valid) => {
    if (valid) {
      bindIsSending.value = true;
      bindCountdown.value = 60; // 设置倒计时为60秒
      const data = await CommonAPI.captchaSmse({ mobile: bindFormData.mobile });
      console.log(data);
      const interval = setInterval(() => {
        bindCountdown.value--;
        if (bindCountdown.value <= 0) {
          clearInterval(interval);
          bindIsSending.value = false;
        }
      }, 1000);
      ElMessage.success("验证码已发送，请注意查收");
    } else {
      ElMessage.error("请输入有效的手机号码");
    }
  });
};

// 获取绑定员工数据
const bindFormRef = ref();
const userData = ref(null);
const handleSearch = () => {
  TermAPI.getMerchantUserByVirtual({
    mobile: bindFormData.mobile,
  }).then((data) => {
    userData.value = data;
  });
};
const handleBindSubmit = () => {
  bindFormRef.value.validate(async (valid) => {
    if (valid) {
      emit("handleBindSubmit", {
        id: props.defaultRowId,
        employeeId: userData.value.userId,
        bindingType: 1,
        mobile: bindFormData.mobile,
        code: bindFormData.code,
      });
    }
  });
};
/**
 * -----------
 * 新增员工
 *
 *
 *
 *
 */
const addEmployeFormData = reactive({
  phone: "",
  code: "",
  nickname: "",
});
const addEmployeRules = reactive({
  phone: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入有效的手机号码", trigger: "blur" },
  ],
  code: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { len: 6, message: "验证码长度为6位", trigger: "blur" },
  ],
  nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
});
const addEmployeIsSending = ref(false);
const addEmployeCountdown = ref(0);
const addEmployeFormRef = ref();
const sendAddEmployeCode = () => {
  addEmployeFormRef.value.validateField("mobile", async (valid) => {
    if (valid) {
      addEmployeIsSending.value = true;
      addEmployeCountdown.value = 60; // 设置倒计时为60秒
      const data = await CommonAPI.captchaSmse({ mobile: addEmployeFormData.phone });
      console.log(data);
      const interval = setInterval(() => {
        addEmployeCountdown.value--;
        if (addEmployeCountdown.value <= 0) {
          clearInterval(interval);
          addEmployeIsSending.value = false;
        }
      }, 1000);
      ElMessage.success("验证码已发送，请注意查收");
    } else {
      ElMessage.error("请输入有效的手机号码");
    }
  });
};
const submitAddEmploye = () => {
  addEmployeFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const data = await TermAPI.addMerchantUserByVirtual({
          mobile: addEmployeFormData.phone,
          code: addEmployeFormData.code,
          nickname: addEmployeFormData.nickname,
        });
        ElMessage.success("新增成功,请绑定员工");
        console.log(data);
      } catch (error) {
        ElMessage.error("新增失败");
      }
    }
  });
};

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  emit("update:modelValue", false); // 关闭弹窗
}
// 监听外部传入的 modelValue，更新内部 visible 状态
watch(
  () => props.modelValue,
  (newValue) => {
    dialog.visible = newValue;
  }
);
</script>
<style style="scss" scoped>
::v-deep(.el-tabs__content) {
  min-height: 100px;
  display: flex;
  align-items: center;
}
</style>
